package com.qhit.dao;

import com.qhit.util.BeanHandler;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;

/**
 * TODO
 *
 * @author 村头老杨头
 * @version 1.0
 * @date 2021/9/29 15:44
 */
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;
    static {
        //读取配置文件
        Properties properties = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //加载驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //创建连接
    public Connection getConnection() throws Exception {
        //创建连接
        if(conn == null){
            conn = DriverManager.getConnection(url, username, password);
        }
        return conn;
    }
    //查询  执行SQL 0~n [1,3] [1]
    public List executeQuery(String sql, Class clz, Object ...objs){
        List list=null;
        try {
            //创建连接
            Connection connection = getConnection();
            //SQL预处理
            ps = connection.prepareStatement(sql);
            //问号填充
            for (int i = 0; i < objs.length; i++) {
                ps.setObject(i+1,objs[i]);
            }
            //发送SQL语句并返回结果集
            rs = ps.executeQuery();
            list = BeanHandler.handler(clz, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    //增删改
    public int executeUpdate(String sql, Object ...objs){
        try {
            Connection conn = getConnection();
            ps = conn.prepareStatement(sql);
            //问号填充
            for (int i = 0; i < objs.length; i++) {
                ps.setObject(i+1,objs[i]);
            }
            //发送SQL语句并返回结果集
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    //关闭
    public void close(){
        try{
            if (rs!=null){
                rs.close();
            }
            if (ps!=null){
                ps.close();
            }
            if (conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
